import wepy from 'wepy'
import api from './api'

/**
 * 权限服务类
 */
export default class Auth {
  static async storageKey(key, value) {
    await wepy.setStorage({key: key, data: value})
    wepy.$instance.globalData[key] = value
  }

  /**
   * 获取用户信息
   */
  static async login() {
    try {
      // 重新登录
      await this.doLogin()
      // 获取用户信息
      const rawUser = await wepy.getUserInfo()
      console.log('[用户信息]', rawUser)
      // 解密信息
      const result = await this.decodeUserInfo(rawUser)
      console.log('保存后的用户', result)
      if (result.errMsg) return false
      await this.storageKey('loginUser', result.user)
      await this.storageKey('company', result.company)
      await this.storageKey('member', result.member)
      await this.storageKey('setInfo', result.setInfo)
      return true
    } catch (error) {
      console.error('[auth] 授权失败', error)
      return false
    }
  }

  /**
   * 服务端解密用户信息
   */
  static async decodeUserInfo(rawUser) {
    const param = {
      'rawData': rawUser.rawData,
      'signature': rawUser.signature,
      'encryptedData': rawUser.encryptedData,
      'iv': rawUser.iv
    }
    console.log('解密param', param)
    return await api.apiWeChatUserInfo(param)
  }

  /**
   * 执行登录操作
   */
  static async doLogin() {
    const {code} = await wepy.login()
    console.log('code', code)
    let token = await this.session(code)
    console.log('[获得token+++结果]', token)
    if (token && token.errMsg) {
      throw token.errMsg
    }
    await this.storageKey('token', token)
    const tokenGlobal = wepy.$instance.globalData.token
    if (tokenGlobal == null || tokenGlobal === '' || tokenGlobal === undefined) {
      throw ('授权失败')
    }
  }

  /**
   * 获取会话
   */
  static async session(jsCode) {

    return await api.apiWeChatLogin(jsCode,this.getCompanyId())
  }

  /**
   * 获取店铺标识符
   */
  static getCompanyId() {
    return wepy.$instance.globalData.companyId
  }

  /**
   * 设置权限值
   */
  static getConfig(key) {
    return wepy.$instance.globalData.auth[key]
  }

  /**
   * 检查是否存在权限制
   */
  static hasConfig(key) {
    const value = this.getConfig(key)
    return value != null && value !== ''
  }

  /**
   * 读取权限值
   */
  static async setConfig(key, value) {
    await wepy.setStorage({key: key, data: value})
    wepy.$instance.globalData.auth[key] = value
  }

  /**
   * 删除权限值
   */
  static async removeConfig(key) {
    console.info(`[auth] clear auth config [${key}]`)
    wepy.$instance.globalData.auth[key] = null
    await wepy.removeStorage({key: key})
  }
}
